package com.sinodata.bsm.cicp.collector.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CommandReader;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description: 
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-20 下午3:36:19          liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class UptimeCollector extends Collector {

    private static final Logger logger = Logger.getLogger(UptimeCollector.class);

    private final long lastTime = 0l;

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String cmd = this.paramMap.get("collectCmd");//采集命令
        String regex = this.paramMap.get("Regex");//正则表达式
        String regexRunTime = "(\\d+):(\\d+).*";
        String regexRunDay = "(\\d+) day.*";
        String regexHour = "(\\d+) h.*";
        String regexMin = "(\\d+) min.*";
        Pattern pattern = Pattern.compile(regex);
        BufferedReader reader = null;
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        String[] propMetas = getPropMeta();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
        try {
            reader = CommandReader.getReader(ip, cmd, (int) this.interval, 0);
            String readLine = null;
            while ((readLine = reader.readLine()) != null) {
                Matcher matcher = pattern.matcher(readLine);
                if (matcher.find()) {
                    int curhour = Integer.parseInt(matcher.group(1));
                    int curmin = Integer.parseInt(matcher.group(2));
                    if (matcher.group(4).equalsIgnoreCase("pm") && curhour < 12) {
                        curhour += 12;
                    }

                    String runTime = matcher.group(5);
                    //int users = Integer.parseInt(matcher.group(6));
                    double load1min = Double.parseDouble(matcher.group(7));
                    double load5min = Double.parseDouble(matcher.group(8));
                    double load15min = Double.parseDouble(matcher.group(9));

                    int days = 0;
                    int hour = 0;
                    int min = 0;

                    pattern = Pattern.compile(regexRunTime);
                    matcher = pattern.matcher(runTime);
                    if (matcher.find()) {
                        hour = Integer.parseInt(matcher.group(1));
                        min = Integer.parseInt(matcher.group(2));
                    }

                    pattern = Pattern.compile(regexRunDay);
                    matcher = pattern.matcher(runTime);
                    if (matcher.find()) {
                        days = Integer.parseInt(matcher.group(1));
                    }

                    pattern = Pattern.compile(regexHour);
                    matcher = pattern.matcher(runTime);
                    if (matcher.find()) {
                        hour = Integer.parseInt(matcher.group(1));
                    }

                    pattern = Pattern.compile(regexMin);
                    matcher = pattern.matcher(runTime);
                    if (matcher.find()) {
                        min = Integer.parseInt(matcher.group(1));
                    }

                    long runTatalTime = days * 24 * 60 + hour * 60 + min;

                    propValues[0] = ResPropertyValue.createPropValue(curhour + ":" + curmin, propMetas[0]);
                    //原来的是 day(s) hour(s) mins(s) 不好看
                    propValues[1] = ResPropertyValue.createPropValue(days + " Days " + hour + " Hours " + min + " Mins", propMetas[1]);
                    propValues[2] = ResPropertyValue.createPropValue(runTatalTime + "", propMetas[2]);
                    //去掉登录用户数的采集
                    //                    propValues[3] = ResPropertyValue.createPropValue(users + "", propMetas[3]);
                    //                    propValues[4] = ResPropertyValue.createPropValue(load1min + "", propMetas[4]);
                    //                    propValues[5] = ResPropertyValue.createPropValue(load5min + "", propMetas[5]);
                    //                    propValues[6] = ResPropertyValue.createPropValue(load15min + "", propMetas[6]);
                    propValues[3] = ResPropertyValue.createPropValue(load1min + "", propMetas[3]);
                    propValues[4] = ResPropertyValue.createPropValue(load5min + "", propMetas[4]);
                    propValues[5] = ResPropertyValue.createPropValue(load15min + "", propMetas[5]);

                    propertyValueX.setValues(propValues);
                    values.add(propertyValueX);
                }
            }
        } catch (Exception e) {
            logger.error("failed to collect by UptimeCollector", e);
            throw new CollectorException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error("failed to close BufferedReader", e);
                }
            }
        }
        return values;
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "collectCmd", "Regex" };
    }

    @Override
    public String[] getPropMeta() {
        //        return new String[] { "主机当前时间", "主机运行时间", "主机运行时间(分钟)", "登录用户数", "过去1分钟平均负载", "过去5分钟平均负载", "过去15分钟平均负载" };
        //        return new String[] { "Current_Host_Time", "Host_Run_Time", "Host_Run_Time_Min", "Login_User_Num", "Avg_Load_Past_One_Minute", "Avg_Load_Past_Five_Minute", "Avg_Load_Past_Fifteen_Minute" };
        //去掉登录用户数
        return new String[] { "Current_Host_Time", "Host_Run_Time", "Host_Run_Time_Min", "Avg_Load_Past_One_Minute", "Avg_Load_Past_Five_Minute", "Avg_Load_Past_Fifteen_Minute" };
    }
}
